package cn.gqr.controller.adm;


import cn.gqr.entity.Largefile;
import cn.gqr.entity.NewBook;
import cn.gqr.service.BookService;
import cn.gqr.service.HotService;
import cn.gqr.tool.RespJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

//后台书本api
@Controller
@RequestMapping("/api/adm/book")
public class BookController {

    @Autowired
    BookService bookService;
    @Autowired
    HotService hotService;

    //书本全查询
    @ResponseBody
    @RequestMapping("/findAll")
    public Map<String,Object> findAll() {
        return RespJson.pack(200,"书本信息",bookService.findAll());
    }

    //id查询
    @ResponseBody
    @RequestMapping("/findById/{bookid}")
    public Map<String,Object> findById(@PathVariable("bookid") int bookid) {
        NewBook book = bookService.findById(bookid);
        if(book==null) {
            return RespJson.pack(200,"没有此id的数据",null);
        }
        return RespJson.pack(200,"ok",book);
    }

    //添加
    @ResponseBody
    @PostMapping("/addBook")
    public Map<String,Object> addBook(NewBook book, @RequestParam(value = "pic",required = false)
            MultipartFile file, Largefile largefile){
        return bookService.bookAddOrUpd(book, file, largefile);
    }


    //分页查询 start起始页,num每页几行
    @ResponseBody
    @RequestMapping("findByPage/{start}/{num}")
    public Map<String,Object> findByPage(@PathVariable("start") int start,@PathVariable("num") int num) {

        List<NewBook> books = bookService.findByPage(start, num);
        //判断数据是不是空的
        if(books.isEmpty()) {
            return RespJson.pack(204,"没有查找到",null);
        }
        Map map = new HashMap();
        map.put("books",books);
        //bookService.findByLine() 总行数
        map.put("total",bookService.findByLine());
        return RespJson.pack(200,"ok",map);
    }


    //根据uuid查询图片,返回这个图片的字节流数据
    //produces = MediaType.IMAGE_JPEG_VALUE 告诉springboot返回的是一个图片
    @ResponseBody
    @RequestMapping(value = "/show/{id}",produces = MediaType.IMAGE_JPEG_VALUE)
    public byte[] show(@PathVariable("id") String id){
        //根据uuid查找,返回一个图片对象
        Largefile obj = hotService.findByPicture(id);
        //把object转换为byte[]
        byte[] buf  = (byte[])obj.getContent();
        return buf;
    }


}